package com.fstec.ks.master.bean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

import org.apache.commons.lang.math.RandomUtils;

import com.sinotn.SinotnLogger;
import com.sinotn.SinotnRuntime;
import com.sinotn.error.MessageException;
import com.sinotn.util.StreamUtil;

public class RegistInfo {
	private String ipAddr;
	private int port;
	private String registId;
	private Date registTime;
	
	public boolean isRegist(){
		return (this.registTime!=null);
	}
	public String getIpAddr() {
		return ipAddr;
	}
	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getRegistId() {
		return registId;
	}
	public void setRegistId(String registId) {
		this.registId = registId;
	}
	public Date getRegistTime() {
		return registTime;
	}
	public void setRegistTime(Date registTime) {
		this.registTime = registTime;
	}
	public void reset() {
		this.registTime=null;
		this.registId=null;
	}
	public boolean isConfig() {
		if(this.ipAddr==null) return false;
		if(this.port==0) return false;
		return true;
	}
	
	private File getDtFile(){
		File home=new File(SinotnRuntime.getHome(), "backup");
		if(!home.exists()){
			home.mkdir();
		}
		home=new File(home, "Queue");
		if(!home.exists()){
			home.mkdir();
		}
		return new File(home,"setting.dt");
	}
	
	private int getRandomSalt(){
		return (127+RandomUtils.nextInt(128));
	}
	public void save() {
		File file=this.getDtFile();
		FileOutputStream fos=null;
		try{
			fos=new FileOutputStream(file);
			int salt=this.getRandomSalt();
			StreamUtil.writeInt(fos, salt);
			StreamUtil.writeText(fos, this.ipAddr, salt);
			StreamUtil.writeInt(fos, this.port);
			if(this.registTime==null){
				StreamUtil.writeLong(fos, 0L);
			}else{
				StreamUtil.writeLong(fos, this.registTime.getTime());
				StreamUtil.writeText(fos, this.registId, salt);
			}
		}catch(Throwable e){
			SinotnLogger.DEBUG.error("保存监控服务器信息发生系统错误",e);
			throw new MessageException("本地保存注册信息失败");
		}finally{
			if(fos!=null){
				try{
					fos.close();
				}catch(Throwable e){}
			}
		}
	}
	public void loadDt() {
		File file=this.getDtFile();
		if(file.exists()){
			FileInputStream fis=null;
			try{
				fis=new FileInputStream(file);
				int salt=StreamUtil.readInt(fis);
				this.ipAddr=StreamUtil.readText(fis, salt);
				this.port=StreamUtil.readInt(fis);
				long timestamp=StreamUtil.readLong(fis);
				if(timestamp>0){
					this.registTime=new Date(timestamp);
					this.registId=StreamUtil.readText(fis, salt);
				}
			}catch(Throwable e){
				this.reset();
				SinotnLogger.DEBUG.error("读取监控服务器信息发生系统错误",e);
			}finally{
				if(fis!=null){
					try{fis.close();}catch(Throwable e){}
				}
			}
		}
	}
}
